<?php
/**
 * Created by PhpStorm.
 * User: an
 * Date: 2015/8/13
 * Time: 15:59
 * editor : zhouzhou
 */
namespace app\admin\api;

use app\admin\model\FreightAddress;
use app\admin\model\FreightTemplate;
use app\common\api\BaseApi;
use app\admin\api\FreightAddressApi;
use app\extend\Page;

class FreightTemplateApi extends BaseApi{

    public function _init() {
        $this->model = new FreightTemplate();
    }

    const ADD             = "admin/FreightTemplateApi/add";
    const ADD_TEMPLATE    = "admin/FreightTemplateApi/addTemplate";
    const DELETE_TEMPLATE = "admin/FreightTemplateApi/deleteTemplate";
    const FIND_TEMPLATE   = "admin/FreightTemplateApi/findTemplate";
    const GET_INFO        = "admin/FreightTemplateApi/getInfo";
    const QUERY           = "admin/FreightTemplateApi/query";
    const QUERY_NO_PAGING = "admin/FreightTemplateApi/queryNoPaging";
    const QUERY_WITH_UID  = "admin/FreightTemplateApi/queryWidthUID";
    const UPDATE_TEMPLATE = "admin/FreightTemplateApi/updateTemplate";
    const GET_FREIGHT_DES = "admin/FreightTemplateApi/getFreightDescribe";
    /**
     * 查询运费描述
     */
    public function getFreightDescribe($template_id = 0 ){
        $result = $this-> model->where(['id'=>$template_id])->getField('type');
        if(false === $result) return $this->apiReturnErr($this-> model->getDbError());
        if(empty($result)) return $this->apiReturnErr('无此运费模板：'.$template_id);
        $msg = ['type'=>$result]; //1=>件，2=>kg，3=>m^3
        $typeMsg = ['','件','kg','m^3'];
        $model  = new FreightAddress();
        $result = $model ->where(['template_id'=>$template_id])->select();
        if(false === $result) return $this->apiReturnErr($model->getDbError());
        if(empty($result)) return $this->apiReturnErr('无此运费模板：'.$template_id);
        if(1===count($result)){
            //不分地区
            $msg['complex'] = 0;
            //计算首份价格
            $price = $result[0];
            $msg['freight'] = $price['firstmoney']; //首份最低运费
            if($price['firstmoney'] == 0){
                $msg['freight'] = 0;
                if($price['replenishmoney'] == 0){
                    $msg['number']  = 0;
                    $msg['msg']     = '包邮';
                }else{
                    if($price['firstpiece']){
                        $msg['number'] = $price['firstpiece'];
                        $msg['msg']    = '前'.$price['firstpiece'].$typeMsg[$msg['type']].'包邮';
                    }else{
                        return $this->apiReturnErr('运费模板设置错误：firstpiece0');
                    }
                }
            }
        }else{
            //分地区
            $msg['complex'] = 1;
            $msg['freight'] = $result[0]['firstmoney'];
            //首份最低运费
            foreach ($result  as $v) {
                if($v['firstmoney'] < $msg['freight']){
                    $msg['freight'] = $v['firstmoney'];
                }
            }
            if($msg['freight'] === 0) $msg['msg'] = '包邮';
            else $msg['msg'] = '';
        }
        return $this->apiReturnSuc($msg);
    }
    /**
     * 根据用户ID查询运费模版
     */
    public function queryWidthUID($uid = -1, $page = ['curpage'=>0,'size'=>10], $order = false, $params = false){

        $query = $this -> model;
        $map   = ['uid' => $uid];
        $query = $query -> relation(true) -> where($map);

        if(false !== $order) $query = $query -> order($order);
        $list = $query->select();

        if(false === $list){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if (false !== $params) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();
        return $this -> apiReturnSuc(["show" => $show, "list" => $list]);

    }

    /**
     * 查询指定运费模版
     */
    public function findTemplate($map){

        $model  = $this -> model;
        $result = $model-> where($map)->relation(true)
        // ->buildSql();
        // return $this->apiReturnErr($result);
        ->find();
        if (false === $result)
            return $this -> apiReturnErr($this -> model -> getDbError());
        else
            return $this -> apiReturnSuc($result);
    }

    /**
     * 添加运费模版
     */
    public function addTemplate($entity){

        $model = $this -> model;
        $result = $model->relation(true)->add($entity);

        if (false === $result)
            return $this -> apiReturnErr($this -> model -> getDbError());
        else
            return $this -> apiReturnSuc($result);
    }
    /**
     * 更新运费模版
     */
    public function updateTemplate($map,$entity){

        //删除旧模版地址数据

        $m = new FreightAddress();
        $m ->startTrans();
        if(isset($map['id'])){

            $result = $m->where(['template_id'=>$map['id']])->delete();
            if (false === $result) {
                $m->rollback();
                return $this -> apiReturnErr($this -> model -> getDbError());
            }
            $m->commit();

        }

        $model = $this -> model;
        $result = $model->relation(true)->where($map)->save($entity);

        if (false === $result)
            return $this -> apiReturnErr($this -> model -> getDbError());
        else
            return $this -> apiReturnSuc($result);

    }

    /**
     * 删除运费模版
     */
    public function deleteTemplate($map){

        $result = $this->model->where($map)->relation(true)->delete();

        if (false === $result)
            return $this -> apiReturnErr($this -> model -> getDbError());
        else
            return $this -> apiReturnSuc($result);
    }

}